package com.leetcode.offer.chapter5;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Dennis Li
 * @date 2020/7/17 14:11
 */
public class SingleNumbers_56 {

    // 位运算
    public int[] singleNumbers(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (!set.contains(num)) set.add(num);
            else set.remove(num);
        }
        int[] ans = new int[2];
        int i = 0;
        for (Integer integer : set) {
            ans[i++] = integer;
        }
        return ans;
    }

    public int[] singleNumbers2(int[] nums) {
        //用于将所有的数异或起来
        int k = 0;

        for (int num : nums) {
            k ^= num;
        }

        //获得k中最低位的1
        int mask = 1;

        //mask = k & (-k) 这种方法也可以得到mask，具体原因百度 哈哈哈哈哈
        int oneBit = Integer.lowestOneBit(k);

        int a = 0;
        int b = 0;

        for (int num : nums) {
            if ((num & mask) == 0) {
                a ^= num;
            } else {
                b ^= num;
            }
        }

        return new int[]{a, b};
    }

}
